/*
 * @Author: tql
 * @Date: 2019-06-19 11:44:24
 * @LastEditTime: 2021-06-15 15:18:58
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /www/NodeSDk/src/index.js
 */
const request = require('request');
const crypto = require('crypto');
const qs = require('qs');
const service = require('./service');


class dtkSdk {
  constructor(props) {
    this.config = {
      ...{
        appKey: '',
        appSecret: '',
        checkSign: 1,
      },
      ...props
    };
    this.service = new service(this.request.bind(this));
  }
  makeSign ($data, $appSecret) {
    /**验签sign参数加密
     * @param $data
     * @param $appSecret
     * @return string
     */
    let $str = '';
    let $index = 0;
    let $sortPor = [];

    for (let key in $data) {
      $sortPor.push(`${key}=${$data[key]}`);
    }
    // 排序
    $sortPor.sort();

    // 转url
    for (let key in $sortPor) {
      $str = `${$str}${$index === 0 ? '' : '&'}${$sortPor[key]}`;
      $index++;
    }

    // md5加密
    const md5 = crypto.createHash('md5');
    const $ret = md5.update(`${$str}&key=${$appSecret}`).digest('hex');

    return $ret;

  }

  makeSignNew (props) {
    // md5加密
    const md5 = crypto.createHash('md5');
    const $ret = md5.update(`appKey=${props.appKey}&timer=${props.timer}&nonce=${props.nonce}&key=${props.appSecret}`).digest('hex');
    return $ret;

  }

  request (url, props) {
    return this.config.checkSign == 2 ? this.newCheckSignRequest(url, props) : this.checkSignRequest(url, props);
  }
  // 老版本验签
  checkSignRequest (url, { form = {}, ...props }) {

    const data = {
      ...{
        version: this.config.version,
        appKey: this.config.appKey,
      },
      ...form
    };

    const options = {
      ...{
        url: url,  //请求地址
        method: 'GET',
        json: true,
        form: {
          ...data,
          ...{ sign: this.makeSign(data, this.config.appSecret) },
        },
      },
      ...props
    };

    return new Promise((resolve, reject) => {
      return request({
        ...options,
        ...({ url: options.method == 'GET' || options.method == 'get' ? `${options.url.indexOf('?') > -1 ? options.url : `${options.url}?`}${qs.stringify(options.form)}` : url }),
        ...({ form: options.method == 'GET' || options.method == 'get' ? {} : options.form })
      }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          //输出返回的内容
          resolve(body)
        } else {
          //输出返回的内容
          reject(response.statusCode, body);
        }
      })
    })

  }

  // 新版本验签名
  newCheckSignRequest (url, { form = {}, ...props }) {

    const data = {
      ...{
        appKey: this.config.appKey,
        appSecret: this.config.appSecret,
      },
    };
    // 计算6位随机值
    const random = (min, max) => {
      return Math.floor(Math.random() * (max - min)) + min;
    }

    // 固定参数
    const parms = {
      nonce: random(100000, 999999),
      timer: (new Date()).getTime(),
    }

    const options = {
      ...{
        url: url,  //请求地址
        method: 'GET',
        json: true,
        form: {
          ...form,
          ...parms,
          ...{ signRan: this.makeSignNew({ ...data, ...parms }), appKey: data.appKey },
        },
      },
      ...props
    };
    // console.log(options)
    return new Promise((resolve, reject) => {
      return request({
        ...options,
        ...({ url: options.method == 'GET' || options.method == 'get' ? `${options.url.indexOf('?') > -1 ? options.url : `${options.url}?`}${qs.stringify(options.form)}` : url }),
        ...({ form: options.method == 'GET' || options.method == 'get' ? {} : options.form })
      }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          //输出返回的内容

          resolve(body)
        } else {
          //输出返回的内容
          reject(response.statusCode, body);
        }
      })
    })

  }

}



module.exports = dtkSdk;
